package com.iiapk.gridnew;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.iiapk.core.widget.TouchInterceptor;
import com.iiapk.grid.database.ColumnTypeManager;
import com.iiapk.gridnew.animation.Rotate3dAnimation;
import com.iiapk.gridnew.domain.ColumnType;

public class DragListTypeActivity extends Activity {   
	
	private ViewGroup mContainer;
    private TouchInterceptor touchInterceptor;
    private ListView listView;
    private ImageView refreshBT;
    
    private ColumnTypeManager columnTypeManager;
    private List<ColumnType> list = new ArrayList<ColumnType>();
    private BaseAdapter adapter;
    private BaseAdapter listAdapter;
    
    private UpdateTask updateTask;
    private RefreshTask refreshTask;
    
    private boolean flag=true;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_type);
        
        mContainer = (ViewGroup) findViewById(R.id.list_panel_fl);
        mContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
        //TextView textView = (TextView)findViewById(R.id.panel_header_text);
		//textView.setText(R.string.listtype_add_title);
        
		findViewById(R.id.panel_header_homeBT).setOnClickListener(
				new OnClickListener(){
			@Override
			public void onClick(View v) {
				finish();
				overridePendingTransition(R.anim.hold,R.anim.push_bottom_out);
			}
		});
		
		refreshBT = (ImageView)findViewById(R.id.panel_header_refreshBT);
		refreshBT.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				beginRefreshTask();
			}
		});
        
        columnTypeManager = new ColumnTypeManager(this);
		list = columnTypeManager.select();
        touchInterceptor = (TouchInterceptor)findViewById(R.id.list_type_listview);
        adapter = new MyAdapter(this);
        touchInterceptor.setAdapter(adapter);
        touchInterceptor.setDropListener(mDropListener);
        //list.setRemoveListener(mRemoveListener);  
        
        listView = (ListView)findViewById(R.id.list_add_listview);
        listAdapter = new MySettingAdapter(DragListTypeActivity.this);
        listView.setAdapter(listAdapter);
    }
    
    private TouchInterceptor.DropListener mDropListener =
        new TouchInterceptor.DropListener() {
        public void drop(int from, int to) {
        	ColumnType item = list.get(from);
        	list.remove(item);
        	list.add(to, item);
        	for(int i=0;i<list.size();i++){
        		list.get(i).idx=i;
        	}
        	adapter.notifyDataSetChanged();
        	listAdapter.notifyDataSetChanged();
        	beginUpdateTask();
        }
    };
    
    private void beginUpdateTask() {
		if (updateTask != null) {
			updateTask.cancel(true);
		}
		updateTask = new UpdateTask();
		updateTask.execute();
	}
    
    private void beginRefreshTask() {
		if (refreshTask != null) {
			refreshTask.cancel(true);
		}
		refreshTask = new RefreshTask();
		refreshTask.execute();
	}
    
    /*private TouchInterceptor.RemoveListener mRemoveListener =
        new TouchInterceptor.RemoveListener() {
        public void remove(int which) {          
        }
    };*/
    
    static class ViewHolder {
		TextView text;
		ImageView icon;
		int flag=1;
	}
    
    class MyAdapter extends BaseAdapter{
    	
    	private LayoutInflater mInflater;
    	Context mContext;
    	private ViewHolder holder;
    	
    	public MyAdapter(Context c){
    		mInflater = LayoutInflater.from(c);
    	}
		public int getCount() {			
			return list.size();
		}
		public Object getItem(int arg0) {
			return list.get(arg0);
		}
		public long getItemId(int arg0) {
			return arg0;
		}
		public View getView(int arg0, View contentView, ViewGroup arg2) {
			if (contentView == null) {
				contentView = mInflater.inflate(R.layout.list_type_item, null);
        		 holder = new ViewHolder();
        		 holder.text = (TextView) contentView.findViewById(R.id.list_type_item_title);
        		 holder.icon = (ImageView) contentView.findViewById(R.id.list_type_item_icon);
        		 contentView.setTag(holder);
			}else {
				holder = (ViewHolder) contentView.getTag();
			}
			holder.text.setText(list.get(arg0).title);
			try {
				Field field = R.drawable.class.getField(list.get(arg0).icon);
				holder.icon.setImageResource((Integer)field.get(field.getName()));
			}catch (Exception e) {
				holder.icon.setImageResource(R.drawable.ic_launcher);
			}
			holder.text.setText(list.get(arg0).title);
			return contentView;
		}
    }
    
    class MySettingAdapter extends BaseAdapter{
    	
    	private LayoutInflater mInflater;
    	Context mContext;
    	private ViewHolder holder;
    	Drawable cancelDrawable;
    	Drawable addDrawable;
    	
    	public MySettingAdapter(Context c){
    		mInflater = LayoutInflater.from(c);
    		addDrawable = getResources().getDrawable(R.drawable.but_icon_add);
    		cancelDrawable = getResources().getDrawable(R.drawable.but_icon_cancel);
    		addDrawable.setBounds(0, 0, addDrawable.getMinimumWidth(), addDrawable.getMinimumHeight());
    		cancelDrawable.setBounds(0, 0, cancelDrawable.getMinimumWidth(), cancelDrawable.getMinimumHeight());
    	}
		public int getCount() {			
			return list.size();
		}
		public Object getItem(int arg0) {
			return list.get(arg0);
		}
		public long getItemId(int arg0) {
			return arg0;
		}
		public View getView(int arg0, View contentView, ViewGroup arg2) {
			View view = mInflater.inflate(R.layout.list_type_add_item, null);
			view.findViewById(R.id.list_type_add_item_img)
				.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					if(holder.flag==0){
						((Button)v).setCompoundDrawables(addDrawable, null, null, null);
						//((Button)v).setCompoundDrawablesWithIntrinsicBounds(R.drawable.but_icon_add, 0, 0, 0);
						((Button)v).setText(R.string.list_add_addtext);
						holder.flag=1;
					}else{
						((Button)v).setCompoundDrawables(cancelDrawable, null, null, null);
						//((Button)v).setCompoundDrawablesWithIntrinsicBounds(R.drawable.but_icon_cancel, 0, 0, 0);
						((Button)v).setText(R.string.list_add_canelext);
						holder.flag=0;
					}
				}
			});
			if (contentView == null) {
				contentView = view;
        		holder = new ViewHolder();
        		holder.text = (TextView) contentView.findViewById(R.id.list_type_add_item_title);
        		holder.icon = (ImageView) contentView.findViewById(R.id.list_type_add_item_icon);
        		contentView.setTag(holder);
			}else {
				holder = (ViewHolder) contentView.getTag();
			}
			try {
				Field field = R.drawable.class.getField(list.get(arg0).icon);
				holder.icon.setImageResource((Integer)field.get(field.getName()));
			}catch (Exception e) {
				holder.icon.setImageResource(R.drawable.ic_launcher);
			}
			holder.text.setText(list.get(arg0).title);
			return contentView;
		}
    }
    
    class RefreshTask extends AsyncTask<String, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			refreshBT.setBackgroundResource(R.anim.main_loading);
			 AnimationDrawable frameAnimation=(AnimationDrawable)refreshBT.getBackground(); 
			    frameAnimation.start(); 
		}
		@Override
		protected Void doInBackground(String... params) {
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if(flag){
				applyRotation(0, 90);
			}else{
				applyRotation(0, -90);
			}
			refreshBT.setBackgroundResource(R.drawable.tab_refresh_selector);
		}
	}

    @Override
    protected void onPause() {
    	super.onPause();
    	overridePendingTransition(R.anim.hold,R.anim.push_bottom_out);
    }
    
    class UpdateTask extends AsyncTask<Integer, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		@Override
		protected Void doInBackground(Integer... params) {
			columnTypeManager.update(list);
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
		}
	}
    
    private void applyRotation(float start, float end) {
        // Find the center of the container
        final float centerX = mContainer.getWidth() / 2.0f;
        final float centerY = mContainer.getHeight() / 2.0f;

        // Create a new 3D rotation with the supplied parameter
        // The animation listener is used to trigger the next animation
        final Rotate3dAnimation rotation =
                new Rotate3dAnimation(start, end, centerX, centerY, 310.0f, true);
        rotation.setDuration(500);
        rotation.setFillAfter(true);
        rotation.setInterpolator(new AccelerateInterpolator());
        rotation.setAnimationListener(new DisplayNextView());
        mContainer.startAnimation(rotation);
    }
    
    private final class DisplayNextView implements Animation.AnimationListener {
        public void onAnimationStart(Animation animation) {
        }
        public void onAnimationEnd(Animation animation) {
            mContainer.post(new SwapViews());
        }
        public void onAnimationRepeat(Animation animation) {
        }
    }
    
    private final class SwapViews implements Runnable {

        public void run() {
            final float centerX = mContainer.getWidth() / 2.0f;
            final float centerY = mContainer.getHeight() / 2.0f;
            Rotate3dAnimation rotation;
            if (flag) {
            	flag=false;
            	touchInterceptor.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				//listView.requestFocus();
				rotation = new Rotate3dAnimation(-90, 0, centerX, centerY, 310.0f, false);
            } else {
            	flag=true;
            	listView.setVisibility(View.GONE);
            	touchInterceptor.setVisibility(View.VISIBLE);
            	//touchInterceptor.requestFocus();
            	rotation = new Rotate3dAnimation(90, 0, centerX, centerY, 310.0f, false);
            }
            rotation.setDuration(500);
            rotation.setFillAfter(true);
            rotation.setInterpolator(new DecelerateInterpolator());
            mContainer.startAnimation(rotation);
        }
    }
    
}